package com.da.javatest.interview.session2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author chenlida
 * @date 2020/3/29 20:58
 *
 * 自旋锁好处：避免了线程上下文切换
 * 坏处：如果线程执行时间较长，其他线程一直占用CPU不释放，会导致系统性能急剧下降
 */
public class Test10SpinLock {
    private AtomicReference<Thread> ar = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + " come in");
        while (!ar.compareAndSet(null, thread)) {

        }
    }

    public void myUnlock() {
        Thread thread = Thread.currentThread();
        ar.compareAndSet(thread, null);
        System.out.println(thread.getName() + " unlock");
    }

    public static void main(String[] args) {
        Test10SpinLock spinLock = new Test10SpinLock();

        new Thread(() -> {
            spinLock.myLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLock.myUnlock();
        }, "AA").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            spinLock.myLock();
            spinLock.myUnlock();
        }, "BB").start();
    }
}
